package cn.ziyoufa.smart.smartschool.okhttp.cookie;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public final class SimpleCookieJar implements CookieJar {
	private final static List<Cookie> allCookies = new ArrayList<>();
	private static SimpleCookieJar simpleCookieJar = null;
	public static List<Cookie> getCookies() {
		return allCookies;
	}

	public static SimpleCookieJar getInstance() {

		if (simpleCookieJar == null) {

			synchronized (SimpleCookieJar.class) {

				if (simpleCookieJar == null) {

					simpleCookieJar = new SimpleCookieJar();
				}
				return simpleCookieJar;
			}
		} else {

			return simpleCookieJar;
		}
	}
	/**
	 * 读取response header中的cookie
	 * @param url
	 * @param cookies
     */
	@Override
	public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
		if(allCookies.size() == 0){
			allCookies.addAll(cookies);
		}
	}
	/**
	 * 发送时向request header中加入cookie
	 * @param url
	 *
	 */
	@Override
	public synchronized List<Cookie> loadForRequest(HttpUrl url) {
		List<Cookie> result = new ArrayList<>();
		for (Cookie cookie : allCookies) {
			if (cookie.matches(url)) {
				result.add(cookie);
			}
		}
		return result;
	}
}
